﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Data.Objects.DataClasses;

using YHWE.Web.Models;
using JULONG.WEB.Library;

namespace YHWE.Web.Areas.manage.Models
{
    using Models;

    public class AccountClass
    {
        DataSession<entityDB2Container, manageUser> entity = new DataSession<entityDB2Container, manageUser>();

        public static bool isLogin
        {
            get
            {
                return HttpContext.Current.Session["loginUserInfo"] != null;
            }
        }

        public static manageUser manageUser
        {
            get
            {
                return HttpContext.Current.Session["loginUserInfo"] as manageUser;
            }
        }

        public static manageUser manageUserForDb
        {
            get
            {
                return HttpContext.Current.Session["loginUserInfo"] as manageUser;
            }
        }

        public bool login(string loginname, string password)
        {
            password = password.MD5();
            var user = entity.query().FirstOrDefault(d => d.loginname == loginname && d.password == password);
            if (user == null || user.ID == 0) return false;
            setSession(user);
            return true;
        }

        public static void logout()
        {
            HttpContext.Current.Session.Remove("loginUserInfo");
        }

        void setSession(manageUser user)
        {
            HttpContext.Current.Session["loginUserInfo"] = user;
        }

        public void upPassword(string newPassword)
        {
            if (!AccountClass.isLogin) throw new Exception("您尚未登录");
            entity.get(d => d.ID == AccountClass.manageUser.ID).password = newPassword.MD5();
            entity.save();
        }



    }

    public class Account : IAccount
    {
        public bool isLogin()
        {
            return AccountClass.isLogin;
        }

        public string getLoginUrl()
        {
            return "/manage/Home/Login";
        }

    }
}